package src;

import com.google.gdata.client.*;
import com.google.gdata.client.youtube.*;
import com.google.gdata.data.*;
import com.google.gdata.data.geo.impl.*;
import com.google.gdata.data.media.*;
import com.google.gdata.data.media.mediarss.*;
import com.google.gdata.data.youtube.*;
import com.google.gdata.data.youtube.YtGender.Value;
import com.google.gdata.data.youtube.YtRelationship.Status;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;

import java.sql.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

@SuppressWarnings("unused")
public class Database_Entry {

	/**
	 * @param args
	 */

	static Statement stmt = null;

	public static void main(String[] args) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("Main!!");
		jdbc();		
		fileread();
		/*
		 * Additional Services
		 * 
		//Recommendation by Youtube
				if (videoEntry.getRelatedVideosLink() != null) {
					  String feedUrl1 = videoEntry.getRelatedVideosLink().getHref();

					  VideoFeed videoFeed1 = service.getFeed(new URL(feedUrl1), VideoFeed.class);
					  printVideoFeed(videoFeed1, true);
					}

		 */
	}

	public static void jdbc(){
		System.out.println("JDBC");

		String userName = "root"; 
		String password = "root";
		String host = "jdbc:mysql://localhost:3306/";
		String dbName = "Youtube";
		Connection conn = null;
		String command ="";

		//Driver testing
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException cnfe) {
			System.out.println("Error loading driver: " + cnfe);
		}
		//Establishing connnection
		String mySqlUrl = host + dbName;
		String embeddedDerbyUrl = "jdbc:derby" + dbName;
		try{
			conn = DriverManager.getConnection(host+dbName,userName,password);
			stmt = conn.createStatement();
		}
		catch(Exception e){
			System.out.println("Error establishing connection to database");
			return;
		}
	}

	public static void fileread()
	{
		System.out.print("\nFile Read!!!!");
		String t;
		try{
			FileReader input = new FileReader("Channels.txt");
			BufferedReader bufRead = new BufferedReader(input);
			String temp;
			while(true)
			{
				t=bufRead.readLine();
				if(t==null)
					break;
				youtubechannnel(t);
				//temp =	"http://gdata.youtube.com/feeds/api/users/" + t.substring(0,(t.length()-4)) ;
				//singer(temp);

			}

		}
		catch(Exception e)
		{
			System.out.println("File error!!");
			return;
		}
	}

	public static void  youtubechannnel(String channel)
	{
		System.out.print("\nChannel!!");
		try
		{
			YouTubeService service = new YouTubeService("Vevo Recommendation");
			//System.out.println("\n\nVideos uploaded by a specific user");
			//Videos uploaded by a specific user
			
			String feedurl1 = "http://gdata.youtube.com/feeds/api/users/" + channel +"/uploads";
			//System.out.print(feedurl1);
			VideoFeed videoFeed1 = service.getFeed(new URL(feedurl1), VideoFeed.class);
			printVideoFeed(videoFeed1, true);
			
			//For singer details
			String feedurl2 = "http://gdata.youtube.com/feeds/api/users/" + channel.substring(0,(channel.length()-4));// +"/uploads";
			singer(feedurl2);
			//VideoFeed videoFeed2 = service.getFeed(new URL(feedUrl2), VideoFeed.class);
			//printVideoFeed(videoFeed2, true);
			//System.out.println("\n\n\n");
			//String temp =
			//		"http://gdata.youtube.com/feeds/api/users/" + channel.substring(0,(channel.length()-4)) ;
			//singer(temp);
		}
		catch(Exception e)
		{
			System.out.print("Error while handling youtube services in Youtube Channel");
			return;
		}
	}


	public static void printVideoFeed(VideoFeed videoFeed, boolean detailed) {
		for(VideoEntry videoEntry : videoFeed.getEntries() ) {
			printVideoEntry(videoEntry, true);
		}
	}

	public static void printVideoEntry(VideoEntry videoEntry, boolean detailed) {
		System.out.print("\nChannel owner Video Print!!");
		YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
		/*
		String query="insert into yvideo values(";
		String title= videoEntry.getTitle().getPlainText();
		if(title=="")
		{
			return;
		}
		else
			query=query+"'"+title+"',";
		//System.out.print("\n!"+title);
		
		String 	Uploaded_by=mediaGroup.getUploader();
		if(Uploaded_by==null)
		{
			query=query+"null,";
		}
		else
			query=query+"'"+Uploaded_by.substring(0, 245)+"',";
			*/
		String id=mediaGroup.getVideoId();
		if(id!=null)
		{
			//query=query+"null,";
			youtubevideo(id);
		}
		/*
		else
			query=query+"'"+id+"',";
		String desc=mediaGroup.getDescription().getPlainTextContent();
		if(desc==null)
		{
			query=query+"null,";
		}
		else
		{
			desc.replaceAll("'"," ");
			query=query+"'"+desc.substring(0, 245)+"',";

		}
		MediaKeywords keywords = mediaGroup.getKeywords();
		String key="";
		//System.out.print("Keywords: ");
		for(String keyword : keywords.getKeywords()) {
			key+=keyword + ",";
		}
		if(key==null)
		{
			query=query+"null,";
		}
		else
			query=query+"'"+key.substring(0, 245)+"',";

		Rating rating = videoEntry.getRating();
		Float rate=rating.getAverage();
		//System.out.println("\nAverage rating: " + rating.getAverage());
		query=query+",";
		YtStatistics stats = videoEntry.getStatistics();
		int count=(int) stats.getViewCount();
		query=query+",";
		//System.out.println("View count: " + stats.getViewCount());
		int fav=(int) stats.getFavoriteCount();
		//System.out.println("Favourite count: " + stats.getFavoriteCount());
		query=query+");";
		//System.out.print(query);
		try{
			stmt.executeUpdate(query);
		}
		catch(Exception e)
		{
			System.out.println("Error executing query or video printing error!!");
			return;
		}*/
	}

	@SuppressWarnings("deprecation")
	public static void  singer(String video)
	{
		//youtubevideo(id);
		//urleg="http://gdata.youtube.com/feeds/api/users/50cent";
		//System.out.print("\nSinger function url-"+video);
		System.out.print("\nSinger!!");
		try{
			YouTubeService service = new YouTubeService("Singer Details");
			UserProfileEntry profileEntry = service.getEntry(new URL(
					video), UserProfileEntry.class);
			//System.out.println("qweasd");
			String query="insert into ysinger values(";
			String user=profileEntry.getUsername();
			if(user==null)
			{
				return;
			}
			query=query+"'"+user.substring(0, 245)+"',";
			//System.out.println("Username: " + user );
			Integer age=profileEntry.getAge();
			if(age==null)
			{
				query=query+"null,";
			}
			else
				query=query+age+",";
			//System.out.println("Before");
			String gender=profileEntry.getGender().toString();
			if(gender==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+gender.substring(0, 245)+"',";
			//System.out.println("After");
			//System.out.println("Username: " + Age );
			String Relationship=profileEntry.getRelationship().toString();
			if(Relationship==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+Relationship.substring(0, 245)+"',";
			//System.out.println("Username: " + Relationship );
			String book=profileEntry.getBooks();
			if(book==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+book.substring(0, 245)+"',";
			//System.out.println("Username: " + book );
			String company=profileEntry.getCompany();
			if(company==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+company.substring(0, 245)+"',";
			//System.out.println("Username: " + company );
			String desc=profileEntry.getDescription();
			if(desc==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+desc.substring(0, 245)+"',";
			//System.out.println("Username: " + desc );
			String hobb=profileEntry.getHobbies();
			if(hobb==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+hobb.substring(0, 245)+"',";
			//System.out.println("Username: " + hobb );
			String Hometown=profileEntry.getHometown();
			if(Hometown==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+Hometown.substring(0, 245)+"',";
			//System.out.println("Username: " + Hometown );
			String Location=profileEntry.getLocation();
			if(Location==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+Location.substring(0, 245)+"',";
			//System.out.println("Username: " + Location );
			String Movies=profileEntry.getMovies();
			if(Movies==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+Movies.substring(0, 245)+"',";
			//System.out.println("Username: " + Movies );
			String Music=profileEntry.getMusic();
			if(Music==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+Music.substring(0, 245)+"',";
			//System.out.println("Username: " + Music );
			String Occupation=profileEntry.getOccupation();
			if(Occupation==null)
			{
				query=query+"null,";
			}
			else
				query=query+"'"+Occupation.substring(0, 245)+"',";
			//System.out.println("Username: " + Occupation );
			String School=profileEntry.getSchool();
			if(School==null)
			{
				query=query+"null";
			}
			else
				query=query+"'"+School.substring(0, 245)+"'";
			//System.out.println("Username: " + School );
			//System.out.println("insert into singer('"+user+"',"+Age+",'"+gender+"','"+Relationship+"','"+book+"','"+company+"','"+desc+"','"+hobb+"','"+Hometown+"','"+Location+"','"+Movies+"','"+Music+"','"+Occupation+"','"+School+"');");
			query=query+");";
			//System.out.print(query);
			stmt.executeUpdate(query);
			//insert into singer('50cent',"null",'"MALE"','"SINGLE"','"null"','"null"','"null"','"null"','"NYC"','"US"','"null"','"null"','"null"','"null"');
			//youtubechannnel(user);
		}
		
		catch(Exception e)
		{
			System.out.println("Singer details cannot be printed!!");
			return;
		}

	}

	
	public static void  youtubevideo(String video)
	{
		System.out.print("\nVideo func!!");
		try{


			YouTubeService service = new YouTubeService("Vevo Recommendation");
			//System.out.println("Details of a specific video");
			//Printing details for a specific video
			String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/"+ video;
			//System.out.print("\nVideo: "+video);
			VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);
			printVideoEntry1(videoEntry, true);
			/*
			String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0";
			VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);
			printVideoEntry(videoEntry, true);
			*/
		}
		catch(Exception e)
		{
			System.out.println("Error contacting Youtube in youtubevideo!!");
			System.out.println(e);
			return;
		}

	}
	
	public static void printVideoEntry1(VideoEntry videoEntry, boolean detailed) {
		System.out.print("\nPrint video details!!");
		String query="insert into yvideo values(";
		String title= videoEntry.getTitle().getPlainText();
		if(title==null)
		{
			return;
		}
		else
		{
			if(title.length()>250)
			{
				title=title.substring(0,245);
			}
		//System.out.print("Title:  "+title);
			query=query+"'"+title+"',";
		//System.out.print("\n!"+title);
		//System.out.print("\nAfterOO!!" + query);
			
		}
		YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
		String 	Uploaded_by=mediaGroup.getUploader();
		//System.out.print("\nAfterOO!!" + query);
		if(Uploaded_by==null)
		{
			query=query+"null,";
		}
		else
		{
			if(Uploaded_by.length()>250)
			{
				Uploaded_by=Uploaded_by.substring(0,245);
			}
		//System.out.print("Title:  "+title);
			query=query+"'"+Uploaded_by+"',";
		//System.out.print("\n!"+title);
		//System.out.print("\nAfterOO!!" + query);
			
		}
		String id=mediaGroup.getVideoId();
		if(id==null)
		{
			query=query+"null,";
		}
		else
		{
			if(id.length()>250)
			{
				id=id.substring(0,245);
			}
		//System.out.print("Title:  "+title);
			query=query+"'"+id+"',";
		//System.out.print("\n!"+title);
		//System.out.print("\nAfterOO!!" + query);
			
		}
		
		String desc=mediaGroup.getDescription().getPlainTextContent();
		if(desc==null)
		{
			query=query+"null,";
		}
		else
		{
			desc.replaceAll("'"," ");
			if(desc.length()>250)
			{
				desc=desc.substring(0,245);
			}
		//System.out.print("Title:  "+title);
			query=query+"'"+desc+"',";
		//System.out.print("\n!"+title);
		//System.out.print("\nAfterOO!!" + query);
			
		}

		
		MediaKeywords keywords = mediaGroup.getKeywords();
		String key="";
		//System.out.print("Keywords: ");
		for(String keyword : keywords.getKeywords()) {
			key+=keyword + ",";
		}
		if(key==null)
		{
			query=query+"null,";
		}
		else
		{
			
			if(key.length()>250)
			{
				key=key.substring(0,245);
			}
		//System.out.print("Title:  "+title);
			query=query+"'"+key+"',";
		//System.out.print("\n!"+title);
		//System.out.print("\nAfterOO!!" + query);
			
		}

		Rating rating = videoEntry.getRating();
		Float rate=rating.getAverage();
		//System.out.println("\nAverage rating: " + rating.getAverage());
		query=query+rate+",";
		YtStatistics stats = videoEntry.getStatistics();
		int count=(int) stats.getViewCount();
		query=query+count+",";
		//System.out.println("View count: " + stats.getViewCount());
		int fav=(int) stats.getFavoriteCount();
		//System.out.println("Favourite count: " + stats.getFavoriteCount());
		query=query+fav+");";
		query.replace("'", " ");
		query.replace("`", " ");
		//System.out.print(query);
		try{
			//System.out.print("Executing query!!");
			stmt.executeUpdate(query);
		}
		catch(Exception e)
		{
			System.out.println("Error executing query or video printing error!!");
			return;
		}
	}

}
